from django.contrib import admin
from .models import CouponModel,CouponLogModel,CouponDepartmentModel

from django_redis import get_redis_connection
import json
# Register your models here.

class CouponDepartmentAdmin(admin.TabularInline):
    model = CouponDepartmentModel
    list_display = ('id','name')


class CouponModelAdmin(admin.ModelAdmin):
    inlines = [CouponDepartmentAdmin]
    list_display = ('id', 'name', 'get_type', 'coupon_type', 'total', 'has_total', 'start_time', 'end_time')

admin.site.register(CouponModel, CouponModelAdmin)


class CouponLogModelAdmin(admin.ModelAdmin):
    list_display = ('id', 'user', 'coupon', 'use_status', 'use_time')

    def save_model(self,request, obj, form, change):
        obj.save()

        redis = get_redis_connection('coupon')
        if obj.use_status == 0 and obj.use_time == None:
            pipe = redis.pipeline()
            pipe.multi()

            coupon_dict = {
                "coupon_id": obj.coupon.id,
                "name": obj.coupon.name,
                "discount_type": obj.coupon.discount_type,
                "get_discount_type_display":obj.coupon.get_discount_type_display(),
                "coupon_type": obj.coupon.coupon_type,
                "get_coupon_type_display":obj.coupon.get_coupon_type_display(),
                "get_type": obj.coupon.get_type,
                "get_get_type_display":obj.coupon.get_get_type_display(),
                'start_time': obj.coupon.start_time.strftime("%Y-%m-%d %H:%M:%S"),
                'end_time': obj.coupon.end_time.strftime("%Y-%m-%d %H:%M:%S"),
                'condition': obj.coupon.condition,
                'sale': obj.coupon.sale,
                'use_status': obj.use_status,
                "cd_department":json.dumps(list(obj.coupon.cd_coupon.values("department__id","department__name"))),
            }
            pipe.hset(f"{obj.user.id}:{obj.id}",mapping=coupon_dict)
            print(f"{obj.user.id}:{obj.id}")
            from datetime import datetime

            pipe.expire(f"{obj.user.id}:{obj.id}",int(obj.coupon.end_time.timestamp()-datetime.now().timestamp()))
            pipe.execute()
        else:
            redis.delete(f"{obj.user.id}:{obj.id}")

    def delete_model(self, request, obj):
        redis = get_redis_connection('coupon')
        redis.delete(f"{obj.user.id}:{obj.id}")
        obj.delete()

    def delete_queryset(self, request, queryset):
        redis = get_redis_connection('coupon')
        for i in queryset:
            redis.delete(f"{i.user.id}:{i.id}")
        queryset.delete()





admin.site.register(CouponLogModel, CouponLogModelAdmin)











